package com.visionblue.business.ship.page.applications

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.visionblue.business.ship.base.BaseViewModel
import com.visionblue.business.ship.base.ViewState
import com.visionblue.business.ship.model.Results
import com.visionblue.business.ship.model.bean.response.ApplicationDetail
import com.visionblue.business.ship.model.bean.response.ListBean
import com.visionblue.business.ship.model.repository.db.RecordAndOrderRelation
import com.visionblue.business.ship.page.applications.ApplicationsRepository
import kotlinx.coroutines.launch

/**
 * @author: xlh
 * @date: 2020-05-28 3:18 PM
 * @desc:
 */
abstract class AbsApplicationsViewModel(private val repo: ApplicationsRepository) :
    BaseViewModel() {
    // 任务列表
    val applicationsState = MutableLiveData<ViewState<ListBean<ApplicationDetail>>>()

    //  任务列表当前页码
    var currPage: Int =
        PAGE_START

    var totalElements: Int = -1

    fun getApplications() {
        viewModelScope.launch {
            checkState(applicationsState, Results.Loading)
            val applicationStatuses = getApplicationStatus()

            val statuses = if (applicationStatuses.size == 1) {
                null
            } else {
                applicationStatuses.joinToString(separator = ",")
            }

            val status = if (applicationStatuses.size == 1) {
                applicationStatuses[0]
            } else {
                null
            }

            checkState(
                applicationsState,
                repo.getApplications(
                    page = currPage,
                    size = 1,
                    status = status,
                    statuses = statuses
                )
                , successAction = { listBean, b ->
                    totalElements = listBean?.totalElements ?: 0
                    applicationsState.value =
                        ViewState(data = listBean, isSuccess = true, isLoadMore = b)
                }
            )
        }
    }

    fun resetPageNum() {
        currPage =
            PAGE_START
    }


    fun prePage() {
        currPage--
        getApplications()
    }

    fun nextPage() {
        currPage++
        getApplications()
    }

    fun getApplicationsAfterOperation() {
        if (currPage >= totalElements) currPage--
        if (currPage < 1) {
            currPage = 1
        }
        getApplications()
    }

    abstract fun getApplicationStatus(): List<Int>

    companion object {
        private const val PAGE_START = 1
    }

}